<template>

  <div class="border">
    <el-form :model="loginForm" class="login-box">
      <h3 class="login-title" style="color: #888888">请登录</h3>
      <el-form-item label="登录名" prop="name">
        <el-input type="text" v-model="loginForm.name" style="width:200px" size="small"></el-input>
      </el-form-item>
      <el-form-item label="密&emsp;码" prop="pswd">
        <el-input type="password" v-model="loginForm.pswd" style="width:200px" size="small"></el-input>
      </el-form-item>
      <el-form-item style="position: relative; left:20%">
        <el-button class="el-button" @click="login" style="width: 150px; ">登录</el-button>
      </el-form-item>
    </el-form>
    <div>{{ errorMsg }}</div>
  </div>
</template>
<script setup>
//import ref from 'vue';
import { reactive } from 'vue';
import router from "@/util/router"
import http from '@/axios/http';
import qs from "qs";
import { useUserStore } from '@/store/userStore'


const loginForm = reactive({
  name: '',
  pswd: ''
});
let errorMsg = reactive('');

const login = async () => {
  // 表单验证
  if (!loginForm.name || !loginForm.pswd) {
    ElMessage.error('请输入用户名和密码');
    return;
  }

  const logindata = {
    username: loginForm.name,
    password: loginForm.pswd
  };

  try {
    const res = await http.post('/lyy/login', qs.stringify(logindata));
    const result = res.data;

    if (result.result === "success") {
      const loginUser = result.data;
      // const token = loginUser.token;
      const userStore = useUserStore();
      console.log('登录返回的 Token:', loginUser.token);
      userStore.setToken(loginUser.token);
      userStore.setUserinfo(loginUser);
      console.log("登录用户信息:", loginUser)
      // 在登录成功的回调中
      userStore.setUserrole(loginUser.roleId);
      console.log("登录用户角色:", loginUser.roleId);
      console.log("存储后的 Token:", userStore.getToken);

      // 登录成功后跳转
      router.push({
        path: '/',
        state: result.data
      });
      console.log("登录响应数据:", result.data);
    } else {
      errorMsg = result.error;
      ElMessage.error(result.error || '登录失败，请稍后重试');
    }
  } catch (error) {
    console.error('登录请求失败:', error);
    ElMessage.error('服务器错误，请稍后重试');
  }
};
</script>

<style scoped>
/* 这里可以添加自定义样式 */

.login-box {
  background-color: azure;
  height: 100%;
  width: 350px;
  margin: 120px auto;
  border: 1px solid #DCDFE6;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 0 30px #DCDFE6;
}

.login-title {
  text-align: center;
}
</style>